package com.kingbook.starter;

import com.kingbook.api.filter.CorsFilter;
import com.kingbook.api.filter.LoginFilter;
import com.kingbook.common.cache.JedisConfig;
import com.kingbook.common.cache.JedisFactory;
import com.kingbook.common.cache.JedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement
@EnableScheduling
@EnableAsync
@PropertySource({"classpath:application.yml"})
@ComponentScan({"com.kingbook"})
public class BootApplication {

    private static final Logger logger = LoggerFactory.getLogger(BootApplication.class);

    @Value("${spring.application.name}")
    private String applicationId;

    @Value("${login.filter}")
    String[] fiters;

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(BootApplication.class, args);
        Environment env = ctx.getEnvironment();
        logger.info("################   Spring Boot Application: {}-{}  #################", env.getProperty("spring.application.name"), env.getProperty("spring.profiles.active"));
    }

    @Bean
    public FilterRegistrationBean corsFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new CorsFilter());
        registration.addUrlPatterns("*");
        registration.setName("CorsFilter");
        registration.setOrder(1);
        return registration;
    }

    @Bean
    public FilterRegistrationBean loginFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new LoginFilter());
        registration.addUrlPatterns(fiters);     //需要登陆验证的url pattern
        registration.setName("LoginFilter");
        registration.setOrder(2);
        return registration;
    }


    @Bean
    public JedisUtils getJedisPool(JedisConfig config){
        return JedisFactory.getJedisUtils(config);
    }

}